<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>合计:{{ total }}条数据</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployeeFn">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" width="70px" type="index" :index="indexdex" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img v-imgerror="defaultImg" class="staff" :src="row.staffPhoto||nullImage">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <!-- 对聘用形式返回的数据进行二次处理 -->
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formaData" />
          <el-table-column label="部门" prop="departmentName" />
          <!-- 利用作用域插槽对时间进行二次处理 -->
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ formateFn(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}"> <!--利用作用域插槽找到当前一行的id -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="deldata(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[10,20,30,40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
      <assign-role :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getListAPI, delDataAPI } from '@/api/employees'
import employees from '@/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import avatar from '@/assets/common/bigUserHeader.png'
import AssignRole from './components/assign-role'
export default {
  name: 'Employees',
  components: {
    addEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      total: 0,
      list: [],
      loading: false,
      showDialog: false,
      defaultImg: avatar,
      nullImage: 'http://heimamianjing-1315206099.cos.ap-beijing.myqcloud.com/1669080961265%E8%87%AD%E5%AE%9D.jpg',
      showRoleDialog: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 分配管理的弹窗 赋值id 打开弹窗
    editRole(id) {
      this.userId = id
      this.showRoleDialog = true
    },
    // excle导出文件
    async exportExcel() {
      // 点击导出调用方法 引入js文件 这种导入方式会得到一个promise所以用.then获取
      // .then后面的excel就代表导入的js文件
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const { data: { rows }} = await getListAPI(1, this.total)
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const data = this.formatJson(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: data, // 必须是个二维数组 具体数据 必填
          filename: 'excel-list', // 非必填（导出的文件名）
          autoWidth: true, // 非必填（单元格宽度是否自适应）
          bookType: 'xlsx' // 非必填（文件名）
        })
      })
    },
    // 处理返回的全部数据处理
    formatJson(rows, headersArr, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const tempArray = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          // 对聘用形式进行处理
          if (englishKey === 'formOfEmployment') {
            const hireObj = employees.hireType.find(item => item.id === Number(value))
            value = hireObj ? hireObj.value : '未知'
          }
          // 对时间格式进行处理
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = this.formateFn(value)
          }
          tempArray.push(item[englishKey])
        })
        arr.push(tempArray)
      })
      return arr
    },
    addEmployeeFn() {
      this.showDialog = true
    },
    deldata(id) {
    //  删除是敏感操纵询问是否确定.then是点击确定
      this.$confirm('确定删除员工？', '温馨提示').then(async() => {
        await delDataAPI(id) // 调用删除接口
        if (this.list.length === 1 && this.page > 1) {
          // 判断当前是否只有一条数据 是的话pag--
          this.page--
        }
        this.getList() // 重新渲染页面
        this.$message.success('删除成功!') // 操作成功提示
      }).catch(() => { })
    },
    // 利用作用域插槽对时间数据进行二次处理的函数
    formateFn(time) {
      return dayjs(time).format('YYYY-MM-DD')
    },
    // 利用formatter属性对数据进行二次处理
    formaData(row, column, cellvalue, index) {
      const hireObj = employees.hireType.find(item => item.id === Number(cellvalue))
      // console.log(row, column, cellvalue, index)
      // 进行严谨判断
      return hireObj ? hireObj.value : '未知'
    },
    async getList() {
      this.loading = true
      const { data } = await getListAPI(this.page, this.size)
      this.loading = false
      this.total = data.total
      this.list = data.rows
    },
    // 页容量改变
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    // 序号的优化
    indexdex(index) {
      return (this.page - 1) * this.size + index + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
    .staff {
      width: 70px;
      height: 70px;
      border-radius: 50%;
    }
  }
</style>
